package com.hcloud.auth.api.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hcloud.common.core.base.HCloudResult;
import com.hcloud.common.core.constants.CoreContants;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author hepangui
 */
@Slf4j
@Component
@AllArgsConstructor
public class MyAccessDeniedHandler extends OAuth2AccessDeniedHandler {
    private final ObjectMapper objectMapper;

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException authException) throws IOException, ServletException {
        log.info("授权失败，禁止访问 {}", request.getRequestURI());
        response.setCharacterEncoding(CoreContants.UTF8);
        response.setContentType(CoreContants.CONTENT_TYPE);
        System.out.println(authException.getClass().getName());
        System.out.println(authException.getMessage());
        HCloudResult hcloudResult = new HCloudResult();
        PrintWriter printWriter = response.getWriter();
        printWriter.append(objectMapper.writeValueAsString(hcloudResult));
    }
}
